<template>
  <div class="ssh-terminal-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h2>SSH终端</h2>
        <p>安全的Web SSH终端，支持多标签页管理</p>
      </div>
      <div class="header-right">
        <el-button @click="showSessionHistory">
          <el-icon><Clock /></el-icon>
          会话历史
        </el-button>
        <el-button type="primary" @click="newConnection">
          <el-icon><Plus /></el-icon>
          新建连接
        </el-button>
      </div>
    </div>

    <!-- 连接标签页 -->
    <div class="terminal-tabs">
      <el-tabs 
        v-model="activeTab" 
        type="card" 
        closable 
        @tab-remove="closeTab"
        @tab-click="switchTab"
      >
        <el-tab-pane
          v-for="tab in terminalTabs"
          :key="tab.id"
          :label="tab.label"
          :name="tab.id"
        >
          <template #label>
            <div class="tab-label">
              <el-icon :class="getConnectionStatusClass(tab.status)">
                <component :is="getConnectionStatusIcon(tab.status)" />
              </el-icon>
              <span>{{ tab.label }}</span>
              <el-badge 
                v-if="tab.hasNewOutput" 
                is-dot 
                class="activity-badge"
              />
            </div>
          </template>
          
          <div class="terminal-content">
            <SSHTerminal 
              :host-id="tab.hostId" 
              :auto-connect="tab.autoConnect"
              @status-change="(status) => updateTabStatus(tab.id, status)"
              @new-output="() => markTabActivity(tab.id)"
            />
          </div>
        </el-tab-pane>
        
        <!-- 添加新连接标签 -->
        <template #addable>
          <el-button 
            type="text" 
            @click="newConnection"
            class="add-tab-button"
          >
            <el-icon><Plus /></el-icon>
          </el-button>
        </template>
      </el-tabs>
    </div>

    <!-- 新建连接对话框 -->
    <el-dialog
      v-model="showNewConnectionDialog"
      title="新建SSH连接"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form :model="connectionForm" label-width="100px">
        <el-form-item label="选择主机" required>
          <el-select 
            v-model="connectionForm.hostId" 
            placeholder="请选择要连接的主机"
            filterable
            style="width: 100%"
          >
            <el-option-group
              v-for="env in groupedHosts"
              :key="env.name"
              :label="env.name"
            >
              <el-option
                v-for="host in env.hosts"
                :key="host.id"
                :label="`${host.hostname} (${host.ip})`"
                :value="host.id"
                :disabled="host.status !== 'online'"
              >
                <div class="host-option">
                  <span class="host-name">{{ host.hostname }}</span>
                  <span class="host-ip">{{ host.ip }}</span>
                  <el-tag 
                    :type="getStatusType(host.status)" 
                    size="small"
                  >
                    {{ getStatusText(host.status) }}
                  </el-tag>
                </div>
              </el-option>
            </el-option-group>
          </el-select>
        </el-form-item>
        
        <el-form-item label="连接名称">
          <el-input 
            v-model="connectionForm.name" 
            placeholder="自定义连接名称（可选）"
          />
        </el-form-item>
        
        <el-form-item label="终端配置">
          <el-row :gutter="10">
            <el-col :span="8">
              <el-input-number 
                v-model="connectionForm.width" 
                :min="20" 
                :max="300" 
                placeholder="宽度"
              />
            </el-col>
            <el-col :span="8">
              <el-input-number 
                v-model="connectionForm.height" 
                :min="10" 
                :max="100" 
                placeholder="高度"
              />
            </el-col>
            <el-col :span="8">
              <el-select v-model="connectionForm.theme">
                <el-option label="深色主题" value="dark" />
                <el-option label="浅色主题" value="light" />
              </el-select>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showNewConnectionDialog = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="createConnection"
          :disabled="!connectionForm.hostId"
        >
          连接
        </el-button>
      </template>
    </el-dialog>

    <!-- 会话历史对话框 -->
    <el-dialog
      v-model="showHistoryDialog"
      title="SSH会话历史"
      width="80%"
      :close-on-click-modal="false"
    >
      <el-table :data="sessionHistory" v-loading="historyLoading">
        <el-table-column prop="hostname" label="主机名" width="150" />
        <el-table-column prop="host_ip" label="IP地址" width="120" />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getSessionStatusType(row.status)">
              {{ getSessionStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="start_time" label="开始时间" width="160">
          <template #default="{ row }">
            {{ formatTime(row.start_time) }}
          </template>
        </el-table-column>
        <el-table-column prop="end_time" label="结束时间" width="160">
          <template #default="{ row }">
            {{ row.end_time ? formatTime(row.end_time) : '进行中' }}
          </template>
        </el-table-column>
        <el-table-column label="持续时间" width="120">
          <template #default="{ row }">
            {{ formatDuration(row.duration_seconds) }}
          </template>
        </el-table-column>
        <el-table-column prop="command_count" label="命令数" width="100" />
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button 
              size="small" 
              @click="viewSessionCommands(row)"
            >
              查看命令
            </el-button>
            <el-button 
              v-if="row.is_recorded"
              size="small" 
              type="primary"
              @click="downloadRecording(row)"
            >
              下载录制
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="historyPagination.page"
          v-model:page-size="historyPagination.size"
          :page-sizes="[10, 20, 50]"
          :total="historyPagination.total"
          layout="total, sizes, prev, pager, next"
          @size-change="fetchSessionHistory"
          @current-change="fetchSessionHistory"
        />
      </div>
    </el-dialog>

    <!-- 命令历史对话框 -->
    <el-dialog
      v-model="showCommandsDialog"
      title="命令历史"
      width="70%"
      :close-on-click-modal="false"
    >
      <el-table :data="commandHistory" max-height="400">
        <el-table-column prop="command" label="命令" min-width="200" />
        <el-table-column prop="start_time" label="执行时间" width="160">
          <template #default="{ row }">
            {{ formatTime(row.start_time) }}
          </template>
        </el-table-column>
        <el-table-column prop="duration" label="耗时(秒)" width="100" />
        <el-table-column prop="exit_code" label="退出码" width="80" />
        <el-table-column label="危险" width="80">
          <template #default="{ row }">
            <el-tag v-if="row.is_dangerous" type="danger" size="small">
              危险
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Clock, Plus, Monitor, CircleCheckFilled, CircleCloseFilled, 
  Loading, WarningFilled
} from '@element-plus/icons-vue'
import SSHTerminal from '@/components/ssh/SSHTerminal.vue'
import api from '@/utils/api'

// 响应式数据
const activeTab = ref('')
const terminalTabs = ref([])
const hostList = ref([])
const sessionHistory = ref([])
const commandHistory = ref([])
const historyLoading = ref(false)

// 对话框状态
const showNewConnectionDialog = ref(false)
const showHistoryDialog = ref(false)
const showCommandsDialog = ref(false)

// 表单数据
const connectionForm = reactive({
  hostId: null,
  name: '',
  width: 80,
  height: 24,
  theme: 'dark'
})

// 分页
const historyPagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 计算属性
const groupedHosts = computed(() => {
  const groups = {}
  hostList.value.forEach(host => {
    const envName = host.environment_name || '未分组'
    if (!groups[envName]) {
      groups[envName] = { name: envName, hosts: [] }
    }
    groups[envName].hosts.push(host)
  })
  return Object.values(groups)
})

// 获取主机列表
const fetchHostList = async () => {
  try {
    const response = await api.get('/cmdb/hosts/')
    if (response.data.success) {
      hostList.value = response.data.data.results || response.data.data
    }
  } catch (error) {
    console.error('获取主机列表失败:', error)
  }
}

// 获取会话历史
const fetchSessionHistory = async () => {
  try {
    historyLoading.value = true
    const params = {
      page: historyPagination.page,
      page_size: historyPagination.size
    }
    
    const response = await api.get('/ssh/sessions/', { params })
    if (response.data.success) {
      sessionHistory.value = response.data.data.results
      historyPagination.total = response.data.data.count
    }
  } catch (error) {
    console.error('获取会话历史失败:', error)
  } finally {
    historyLoading.value = false
  }
}

// 新建连接
const newConnection = () => {
  showNewConnectionDialog.value = true
  // 重置表单
  Object.assign(connectionForm, {
    hostId: null,
    name: '',
    width: 80,
    height: 24,
    theme: 'dark'
  })
}

// 创建连接
const createConnection = () => {
  const selectedHost = hostList.value.find(h => h.id === connectionForm.hostId)
  if (!selectedHost) {
    ElMessage.error('请选择有效的主机')
    return
  }
  
  const tabId = `tab-${Date.now()}`
  const tabLabel = connectionForm.name || `${selectedHost.hostname}`
  
  const newTab = {
    id: tabId,
    label: tabLabel,
    hostId: connectionForm.hostId,
    status: 'connecting',
    autoConnect: true,
    hasNewOutput: false
  }
  
  terminalTabs.value.push(newTab)
  activeTab.value = tabId
  showNewConnectionDialog.value = false
  
  ElMessage.success('正在建立连接...')
}

// 关闭标签页
const closeTab = (tabId: string) => {
  const index = terminalTabs.value.findIndex(tab => tab.id === tabId)
  if (index > -1) {
    terminalTabs.value.splice(index, 1)
    
    // 如果关闭的是当前活跃标签，切换到其他标签
    if (activeTab.value === tabId) {
      if (terminalTabs.value.length > 0) {
        activeTab.value = terminalTabs.value[Math.max(0, index - 1)].id
      } else {
        activeTab.value = ''
      }
    }
  }
}

// 切换标签页
const switchTab = (tab: any) => {
  const tabData = terminalTabs.value.find(t => t.id === tab.name)
  if (tabData) {
    tabData.hasNewOutput = false
  }
}

// 更新标签页状态
const updateTabStatus = (tabId: string, status: string) => {
  const tab = terminalTabs.value.find(t => t.id === tabId)
  if (tab) {
    tab.status = status
  }
}

// 标记标签页有新输出
const markTabActivity = (tabId: string) => {
  const tab = terminalTabs.value.find(t => t.id === tabId)
  if (tab && activeTab.value !== tabId) {
    tab.hasNewOutput = true
  }
}

// 显示会话历史
const showSessionHistory = () => {
  showHistoryDialog.value = true
  fetchSessionHistory()
}

// 查看会话命令
const viewSessionCommands = async (session: any) => {
  try {
    const response = await api.get(`/ssh/sessions/${session.session_id}/commands/`)
    if (response.data.success) {
      commandHistory.value = response.data.data.results
      showCommandsDialog.value = true
    }
  } catch (error) {
    console.error('获取命令历史失败:', error)
    ElMessage.error('获取命令历史失败')
  }
}

// 下载录制文件
const downloadRecording = (session: any) => {
  ElMessage.info('录制下载功能开发中')
}

// 工具函数
const getConnectionStatusClass = (status: string) => {
  const classMap = {
    'connecting': 'status-connecting',
    'connected': 'status-connected',
    'disconnected': 'status-disconnected',
    'error': 'status-error'
  }
  return classMap[status] || ''
}

const getConnectionStatusIcon = (status: string) => {
  const iconMap = {
    'connecting': 'Loading',
    'connected': 'CircleCheckFilled',
    'disconnected': 'CircleCloseFilled',
    'error': 'WarningFilled'
  }
  return iconMap[status] || 'Monitor'
}

const getStatusType = (status: string) => {
  const typeMap = {
    'online': 'success',
    'offline': 'danger',
    'maintenance': 'warning',
    'error': 'danger'
  }
  return typeMap[status] || 'info'
}

const getStatusText = (status: string) => {
  const textMap = {
    'online': '在线',
    'offline': '离线',
    'maintenance': '维护',
    'error': '故障'
  }
  return textMap[status] || '未知'
}

const getSessionStatusType = (status: string) => {
  const typeMap = {
    'connected': 'success',
    'disconnected': 'info',
    'error': 'danger'
  }
  return typeMap[status] || 'info'
}

const getSessionStatusText = (status: string) => {
  const textMap = {
    'connecting': '连接中',
    'connected': '进行中',
    'disconnected': '已断开',
    'error': '错误'
  }
  return textMap[status] || '未知'
}

const formatTime = (time: string) => {
  return new Date(time).toLocaleString()
}

const formatDuration = (seconds: number) => {
  if (!seconds) return '-'
  
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = Math.floor(seconds % 60)
  
  if (hours > 0) {
    return `${hours}h ${minutes}m ${secs}s`
  } else if (minutes > 0) {
    return `${minutes}m ${secs}s`
  } else {
    return `${secs}s`
  }
}

// 生命周期
onMounted(() => {
  fetchHostList()
})
</script>

<style scoped>
.ssh-terminal-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: white;
  border-bottom: 1px solid #e0e0e0;
}

.header-left h2 {
  margin: 0 0 5px 0;
  color: #303133;
}

.header-left p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.header-right {
  display: flex;
  gap: 10px;
}

.terminal-tabs {
  flex: 1;
  padding: 0 20px 20px 20px;
}

.terminal-tabs :deep(.el-tabs) {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.terminal-tabs :deep(.el-tabs__content) {
  flex: 1;
  padding: 0;
}

.terminal-tabs :deep(.el-tab-pane) {
  height: 100%;
}

.tab-label {
  display: flex;
  align-items: center;
  gap: 5px;
  position: relative;
}

.activity-badge {
  position: absolute;
  top: -5px;
  right: -5px;
}

.status-connecting {
  color: #409EFF;
  animation: spin 1s linear infinite;
}

.status-connected {
  color: #67C23A;
}

.status-disconnected {
  color: #909399;
}

.status-error {
  color: #F56C6C;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.terminal-content {
  height: 100%;
}

.add-tab-button {
  padding: 8px;
  margin-left: 10px;
}

.host-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.host-name {
  font-weight: 500;
}

.host-ip {
  color: #909399;
  font-size: 12px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>
